import { toLogin } from './page';
import { error, limitMessage, LimitMessageFunc } from './message';
import { sleep } from './tools';
import { BaseAjax } from 'jwfetch';

export class Ajax extends BaseAjax {
  private msgs: LimitMessageFunc[] = [];

  /**
   * 处理消息
   */
  protected handleMessage(msg: string) {
    this.msgs.push(async () => {
      error(msg);
      await sleep(3000);
    });
    limitMessage(this.msgs);
  }

  /**
   * 处理错误请求
   */
  protected handleErrorResponse(response: Response) {
    console.error(`HTTP error, status = ${response.status}, statusText = ${response.statusText}`);
    if (response.status === 401) { //权限问题
      this.stopAjax();
      this.abortAll();
      toLogin();
    }
  }
}

// @ts-ignore 此处baseURL是从.umirc.ts的define注入
Ajax.defaults.baseURL = baseURL;

export const ajax = new Ajax();
export const get = ajax.get.bind(ajax);
export const post = ajax.post.bind(ajax);

// @ts-ignore
window.ajax = ajax;

// ajax.interceptors.request.use(function(config) {
//   console.log(config);
//   config.headers = config.headers || {};
//   config.headers.token = "abcd";
//   return config;
// }, function(err)  {
//   return Promise.reject(err);
// });
//
// ajax.interceptors.response.use(function(data) {
//   console.log(data);
//   return data.slice(0, 10);
// }, function(err)  {
//   return Promise.reject(err);
// });
